#include <bits/stdc++.h>

using namespace std;

const int MAXN = 4e6+10;

typedef long long ll;
typedef double db;

ll f[MAXN],ans;
int n,m,s[MAXN],num[MAXN],t,maxt,q[MAXN],l,r;

double slope(int a,int b){
	return (double)(f[b] + s[b] - f[a] - s[a])/(num[b] - num[a] == 0 ? 1e-9:(num[b]-num[a]));
}

int main(){
	scanf("%d %d",&n,&m);
	for(int i = 1;i <= n;i++){
		scanf("%d",&t);maxt = max(maxt,t);
		s[t]+=t;num[t]++;
	}
	for(int i = 1;i <= maxt+m;i++) s[i] += s[i-1],num[i] += num[i-1];
	l = 1;
	for(int i = 0;i <= maxt+m;i++){
		if(i >= m){
			while(l < r && slope(q[r-1],q[r]) >= slope(q[r],i-m)) r--;
			q[++r] = i-m;
		}
		f[i] = num[i] * i - s[i];
		while(l < r && slope(q[l],q[l+1]) <= i) l++;
		if(l <= r) f[i] = min(f[q[l]] + num[i] * i - num[q[l]] * i - s[i] + s[q[l]],f[i]);
	}
	ans = 1e18;
	for(int i = maxt;i <= m+maxt;i++) ans = min(ans,f[i]);
	printf("%lld\n",ans);
	return 0;
}
